package com.zx.mobile.controller;

import com.zx.mobile.MobileCommonHelper;
import com.zx.mobile.SessionHelper;
import com.zx.mobile.domain.MobileUserDomain;
import com.zx.mobile.domain.pingan.PAPassportRequest;
import com.zx.mobile.domain.pingan.PAPassportResponse;
import com.zx.platform.utils.DateUtils;
import com.zx.platform.utils.PmpUtils;
import com.zx.scp.utils.PropertyUtil;
import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.lang3.builder.ToStringBuilder;
import org.apache.log4j.Logger;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpServletRequest;
import java.io.UnsupportedEncodingException;
import java.lang.reflect.InvocationTargetException;
import java.util.Date;
import java.util.Map;

/**
 * 对接平安 获取登陆会话 下午8:09 To change this template use File | Settings | File
 * Templates.
 */
@Controller
@RequestMapping("/mobile/index")
public class PingAnGameAccessController {
    /**
     * log
     */
    private static Logger log = Logger
            .getLogger(PingAnGameAccessController.class);

    /**
     * 平安 查询用户余额
     *
     * @param model
     * @param request
     * @return
     */
    @RequestMapping("/paPassport")
    public String passport(Model model, HttpServletRequest request)
            throws IllegalAccessException, InvocationTargetException,
            NoSuchMethodException {
        PAPassportRequest pAPassportRequest = new PAPassportRequest();
        try {
            String paUrl = PropertyUtil.getValue("PAACCESSURL");
            MobileUserDomain user = (MobileUserDomain) request.getSession()
                    .getAttribute(SessionHelper.MOBILEUSER);
            pAPassportRequest.setClient_id(PropertyUtil.getValue("PACLIENTID"));
            pAPassportRequest.setClient_secret(PropertyUtil
                    .getValue("PACLIENTSECRET"));
            pAPassportRequest.setOpenId(user.getMerchantInfoDetailModel()
                    .getMerchantId());
            pAPassportRequest.setResponse_type("code");
            pAPassportRequest.setTimestamp(DateUtils.dateToString(new Date(),
                    "yyyy-MM-dd HH:mm:ss"));
            StringBuilder userStr = new StringBuilder(user
                    .getMerchantInfoDetailModel().getSysAccount())
                    .append(";;;;;");
            String userEn = PmpUtils.encryptMode(PropertyUtil
                    .getValue("PA3DESKEY"), userStr.toString().getBytes());
            pAPassportRequest.setUserInfo(userEn);
            pAPassportRequest.setSign(getSign(pAPassportRequest));
            log.info("send request "
                    + ToStringBuilder.reflectionToString(pAPassportRequest));
            Map<String, String> param = BeanUtils.describe(pAPassportRequest);
            param.remove("class");
            log.info("send sign request " + paUrl);
            PAPassportResponse response = MobileCommonHelper.httpRequest(
                    PAPassportResponse.class, paUrl, param);
            log.info("return response "
                    + ToStringBuilder.reflectionToString(response));
            if ("0000".equals(response.getErrorCode())) {
                model.addAttribute("response", response);
                model.addAttribute("paSecondUrl",
                        PropertyUtil.getValue("PASECONDURL"));
                model.addAttribute("paSecondGoUrl",
                        PropertyUtil.getValue("PASECONDGOURL"));
                return "/jsp/mobile/pingan/hideaccess";
            } else {
                model.addAttribute("errorMsg", "游戏出问题，请稍后重试！");
                return "/jsp/mobile/error";
            }
        } catch (Exception e) {
            model.addAttribute("errorMsg", "游戏出问题，请稍后重试！");
            log.error("游戏出问题", e);
            return "/jsp/mobile/error";
        }
    }

    /**
     * 对请求包体加密
     *
     * @param pAPassportRequest
     * @return
     */
    private static String getSign(PAPassportRequest pAPassportRequest) {
        // SHA1签名： client_id+openId+timestamp+ userInfo+signkey
        StringBuilder str = new StringBuilder();
        str.append(pAPassportRequest.getClient_id())
                .append(pAPassportRequest.getOpenId())
                .append(pAPassportRequest.getTimestamp())
                .append(pAPassportRequest.getUserInfo())
                .append(PropertyUtil.getValue("PASHA1SIGNKEY"));
        String sign = "";
        try {
            sign = DigestUtils.shaHex(str.toString().getBytes("UTF-8"));
        } catch (UnsupportedEncodingException e) {
            log.error("平安游戏对接加密异常", e);
            throw new RuntimeException("平安游戏对接加密异常");
        }
        return sign;
    }
}
